package org.dromara.crawler.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.crawler.domain.CrawlerTask;
import org.dromara.crawler.mapper.CrawlerTaskMapper;
import org.dromara.crawler.service.CrawlerTaskService;

import org.springframework.stereotype.Service;

/**
 * 抓取任务单表Service服务
 *
 * @author shup
 * @date 2025-6-18
 */
@Service
@RequiredArgsConstructor
public class CrawlerTaskServiceImpl extends ServiceImpl<CrawlerTaskMapper, CrawlerTask> implements CrawlerTaskService {

    @Override
    public IPage<CrawlerTask> queryByPage(CrawlerTask crawlerTask, PageQuery pageQuery) {
        return page(pageQuery.build(), createWrapper(crawlerTask));
    }

    @Override
    public boolean deleteTask(Long taskId) {
        return this.removeById(taskId);
    }

    @Override
    public Boolean runTask(Long taskId) {
        CrawlerTask crawlerTask = getById(taskId);
        crawlerTask.setStatus("1");
        return updateById(crawlerTask);
    }

    @Override
    public Boolean stopTask(Long taskId) {
        CrawlerTask crawlerTask = getById(taskId);
        crawlerTask.setStatus("0");
        return updateById(crawlerTask);
    }

    private LambdaQueryWrapper createWrapper(CrawlerTask crawlerTask){
        LambdaQueryWrapper<CrawlerTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(crawlerTask.getTaskName()), CrawlerTask::getTaskName, crawlerTask.getTaskName());
        wrapper.like(ObjectUtil.isNotEmpty(crawlerTask.getKeyWord()), CrawlerTask::getKeyWord, crawlerTask.getKeyWord());
        wrapper.eq(ObjectUtil.isNotEmpty(crawlerTask.getStatus()), CrawlerTask::getStatus, crawlerTask.getStatus());
        if (ObjectUtil.isNotEmpty(crawlerTask.getStartTime()) && ObjectUtil.isNotEmpty(crawlerTask.getEndTime())) {
            wrapper.ge(CrawlerTask::getStartTime, crawlerTask.getStartTime());
            wrapper.le(CrawlerTask::getEndTime, crawlerTask.getEndTime());
        }
        wrapper.orderByDesc(CrawlerTask::getId);
        return wrapper;
    }

}
